<!--
 * @Descripttion: 用户管理
 * @version:
 * @Author: 穆宏宇
 * @Date: 2020-09-21 14:43
 * @LastEditors: 穆宏宇
 * @LastEditTime: 2020-09-27 15:19:21
-->
<template>
	<div>
		<el-row :gutter="10">
			<el-col :span="6">
				<el-card class="box-card" :body-style="{ overflowY: 'auto', height: '74.5vh' }">
					<div slot="header" class="clearfix">
						<i class="el-icon-menu orgIcon"></i>
						<span>组织机构</span>
						<el-input style="margin-top: 10px;" size="small" v-model="filterText" placeholder="请先展开组织再搜索"
							clearable></el-input>
					</div>
					<el-tree ref="space" :data="treeData" node-key="id" :check-on-click-node="true"
						:props="defaultProps" :filter-node-method="filterNode" @node-click="changeOrgTree"
						:load="loadNode" lazy>
						<span class="custom-tree-node" slot-scope="{ node }">
							<span>{{ node.label }}</span>
						</span>
					</el-tree>
				</el-card>
			</el-col>
			<el-col :span="18">
				<el-card class="box-card">
					<!-- 搜索 -->
					<el-form :inline="true" label-width="100px" >
						<div class="topNav">
							<el-button type="text" icon="el-icon-search" style="float:right;" @click="getUserListEvent()">搜索</el-button>
						</div>
						<el-form-item label="用户名">
							<el-input placeholder="输入用户名" v-model="searchData.account" clearable/>
						</el-form-item>			
						<el-form-item label="密码">
							<el-input placeholder="输入密码" v-model="searchData.name" clearable/>
						</el-form-item>			
					</el-form>
					<!-- 表格 -->
					<el-table :data="tableData" border style="width: 100%" :max-height="maxHeightNow">
						<el-table-column type="selection" width="55" align="center"/>
						<el-table-column label="登录名/姓名" width="110">
							<template slot-scope="scope"><strong></strong>
								<p>{{scope.row.account}}</p>
								<p>{{scope.row.name}}</p>
							</template>
						</el-table-column>
						<el-table-column prop="mobile" label="电话" width="150"></el-table-column>
						<el-table-column prop="email" label="邮箱" width="140"></el-table-column>
						<el-table-column prop="roles" label="角色" width="180"></el-table-column>
					    <el-table-column prop="budget" label="预算" width="180"></el-table-column>
						<el-table-column prop="orgName" label="组织" width="180"></el-table-column>
						<el-table-column fixed="right" label="操作" width="300">
							<template slot-scope="scope">
								<el-button type="warning" size="mini" icon="el-icon-success" plain
									@click="updateUserType(scope.row)">设置预算</el-button>
							</template>
						</el-table-column>
					</el-table>
					<!-- 分页 -->
					<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
						:current-page="currentPage" :page-size="pageSize"
						layout="total, sizes, prev, pager, next, jumper" :total="totalPage">
					</el-pagination>
				</el-card>
			</el-col>
		</el-row>
		<!-- editDialog 新增用户 START -->
		<el-dialog title="设置预算" :visible.sync="dialogTypeVisible" width="30%" :before-close="handleRoleClose"
			:close-on-click-modal="false" :close-on-press-escape="false">
			<div class="selectRole">
				<el-form :inline="true">
					<el-row>
						<!-- {{selectRow}} -->
						<el-col :span="24">
							<el-form-item label="预算值(万)">
								<el-input type="number" min="0" v-model="purchseBudget" placeholder="请输入预算值"
								 onkeyup="this.value=this.value.replace(/|^0/g,'');" style="width:100%"
								></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogTypeVisible = false">取 消</el-button>
				<el-button type="primary" @click="confirmPurchasseBudget">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import eControl from '@/components/e-control'
	import eForm from '@/components/e-form'
	import {
		formOptions,
		btns
	} from './control'
	import {
		editFormOptions,
		editFormRules
	} from './form'
	import interFaces from './interFaces'
	import {
		getOrgTree,
		getRoleAll,
		getUserList,
		deleteUser,
		userAddRole,
		resetPasswordApi,
		getOrgTreeLazy,
		getAllOrgList,
		editUserType,
		selectTypeByUserId,
		selectOrgByUserId,
		getRoleCon,
		selectUserInfoByUserId,
		insertUser,
		editUser,
		deleteTUser,
		insertBudgetByUser,
		updateBudgetByUser
	} from '@/api/admin.api'

	import {
		getOrgTreeApi
	} from '@/api/itemPoolApi.js'

	export default {
		name: 'users',
		components: {
			eControl,
			eForm
			// eManage
		},
		data() {
			return {
				formOptions,
				btns,
				// columns,
				editFormOptions,
				editFormRules,
				interFaces,
				dialogRoleVisible: false,
				editDialogShow: false,
				dialogTypeVisible: false,
				editDialogType: 0,
				setRole: '',
				setType: '',
				// 编辑框表单数据
				dialogFormCurrent: {
					orgId: '',
					account: '',
					name: '',
					fax: '',
					email: '',
					tel: '',
					mobile: '',
					UKEY: '',
					status: ''
				},
				// 左侧树
				treeData: [],
				treeData2: [],
				defaultProps: {
					children: 'children',
					label: 'name'
				},
				// 表格数据
				tableData: [],
				currentPage: 1,
				pageSize: 10,
				totalPage: 0,
				rolesArr: [], // 用户权限内的角色
				searchData: {},
				selectUserId: '', // 选中用户的ID
				isOrg: true, // 编辑用户信息，检查是否绑定组织， true 没有组织，false 有组织
				filterText: '',
				orgId1: '', // 树型ID
				newArr1: [],
				orgId2: '', // 树型ID
				newArr2: [],
				orgId3: '', // 树型ID
				newArr3: [],
				orgId4: '', // 树型ID
				newArr4: [],
				orgId5: '', // 树型ID
				newArr5: [],
				orgId6: '', // 树型ID
				newArr6: [],
				orgId7: '', // 树型ID
				newArr7: [],
				orgId8: '', // 树型ID
				newArr8: [],
				orgId9: '', // 树型ID
				newArr9: [],
				orgId10: '', // 树型ID
				newArr10: [],
				orgId11: '', // 树型ID
				newArr11: [],
				orgId12: '', // 树型ID
				newArr12: [],
				lastId: '',
				lastName: '',
				orgNameUser: '',
				orgName2: '',
				purchseBudget:'',
				selectRow:''
			}
		},
		watch: {
			filterText(val) {
				this.$refs.space.filter(val)
			}
		},
		computed: {
			// 表单实例
			dialogForm() {
				return this.$refs.dialogForm
			},
			// 编辑框标题
			editDialogTitle() {
				return this.editDialogType === 0 ? '新增用户' : '编辑用户'
			},
			// 表格高度
			maxHeightNow() {
				const height = window.innerHeight
				return height - 300
			}
		},
		created() {},
		mounted() {
			// 查询权限内的角色
			// this.queryRolesAll()
			this.getOrgTreeEvent()
			// 查询已注册用户
			this.getUserListEvent()
		},
		methods: {
			confirmPurchasseBudget(){
				var that = this;
				//有预算，修改
				if(this.selectRow.purchseBudget){
					updateBudgetByUser({
						purchseBudget:this.purchseBudget
					}).then(res=>{
						if(res>0){
							that.$message.success("设置成功")
						}else{
							that.$message.error("设置是被")
						}
					}).catch(err=>{
						that.$message.error("设置是被")
					})
				}else{
					// 无预算，新增
					insertBudgetByUser({
						purchseBudget:this.purchseBudget
					}).then(res=>{
						if(res>0){
							that.$message.success("设置成功")
							that.dialogTypeVisible = false
						}else{
							that.$message.error("设置是被")
						}
					}).catch(err=>{
						that.$message.error("设置是被")
					})
				}
			},
			changeOrgTree(item) {
				this.orgId = item.id;
				this.orgId2 = item.id;
				this.orgName2 = item.name;
				this.orgCode = item.code;
				this.orgName = item.name;
				this.getUserListEvent()
			},
			changeOrgTree2(item) {
				this.orgId2 = item.id;
				this.orgCode2 = item.code;
				this.orgName2 = item.name;
			},
			cancelOrg() {
				this.orgId2 = this.$refs.dialogForm.formData.orgId
				this.orgName2 = "";
			},
			updateUserType(rowData) {
				// 修改用户身份
				var that = this;
				this.dialogTypeVisible = true;
				this.selectRow = rowData;
			},
			getDepList(t) {
				var that = this;
				// getOrgTreeApi(t).then((res) => {
				// 	that.newArr1 = res;
				// })
				this.getOrgTreeEvent2();
			},
			// 获取组织的ids
			collectId(data, id) {
				const list = []
				getAll(data, id)

				function getAll(data, id) {
					for (let i = 0; i < data.length; i++) {
						const cur = data[i]
						const aa = findPnodeId(cur, id)
						if (aa && aa !== '0') {
							list.unshift(aa)
							getAll(data, aa)
						}
					}
				}

				function findPnodeId(data, id) {
					let result
					if (!data) {
						return
					}
					for (let i = 0; i < data.children.length; i++) {
						const item = data.children[i]
						if (item.id === id) {
							result = data.id
							return result
						} else if (item.children && item.children.length > 0) {
							result = findPnodeId(item, id)
							if (result) {
								return result
							}
						}
					}
					return result
				}

				return [...list, id]
			},
			/**
			 * @description 复合条件查询列表用户列表
			 * @author 穆宏宇
			 * @date 2020-09-24 13:34:09
			 * @param
			 * @return
			 * */
			getUserListEvent() {
				const params = {
					pageSize: this.pageSize,
					pageNum: this.currentPage,
					account: this.searchData.account,
					name: this.searchData.name
				}
				// if (this.orgId) {
				// 	params['orgId'] = this.orgId
				// }
				if (this.orgCode) {
					params['orgCode'] = this.orgCode
				}
				if (this.searchData.account || this.searchData.name || this.orgCode) {
					selectUserInfoByUserId(params).then(res => {
						// console.log('111res',res)
						this.tableData = res.rows
						this.totalPage = res.total
					})
				}
			},
			// 获取组织树
			getOrgTreeEvent() {
				var that = this;
				getOrgTreeApi('0').then(res => {
					that.treeData = res
					this.$nextTick(() => {
						this.$set(this.editFormOptions[0].props, 'options', that.treeData)
					})
					console.log(that.treeData)
				})
				that.form = {};
			},
			getOrgTreeEvent2() {
				var that = this;
				getOrgTreeApi('0').then(res => {
					that.treeData2 = res
					console.log(that.treeData)
				})
			},
			// 组织机构节点数据
			loadNode(node, resolve) {
				getOrgTreeApi(node.data.id).then((res) => {
					if (node.data.type < 4) {
						return resolve(res)
					} else {
						return resolve([])
					}
				})
			},
			/**
			 * @description 查询权限内的角色
			 * @author 穆宏宇
			 * @date 2020-09-24 09:19:23
			 * @param
			 * @return
			 * */
			queryRolesAll() {
				// getRoleAll().then((response) => {
				// 	this.rolesArr = response
				// })
				var that = this;
				getRoleCon({
					pageNum: 1,
					pageSize: 1000
				}).then((response) => {
					that.rolesArr = response.rows;
				})
			},
			handleOther(data) {
				console.log(data)
			},
			// changeTree(item) {
			// 	this.orgId = item.id
			// 	this.orgCode = item.code
			// 	// 查询已注册用户
			// 	this.getUserListEvent()
			// },
			// changeTree2(item) {
			// 	this.orgId = item.id
			// 	this.orgName = item.name
			// 	// 查询已注册用户
			// },
			//优化之后的代码 不管有几级都可以适用,不过用了递归
			filterNode(value, data, node) {
				console.log(value, data, node)
				if (!value) {
					return true
				}
				let _array = [] //这里使用数组存储 只是为了存储值。
				this.getReturnNode(node, _array, value)
				let result = false
				_array.forEach(item => {
					result = result || item
				})
				return result
			},
			getReturnNode(node, _array, value) {
				let isPass = node && node.label && node.label.indexOf(value) !== -1
				isPass ? _array.push(isPass) : ''
				if (!isPass && node.level != 1 && node.parent) {
					this.getReturnNode(node.parent, _array, value)
				}
			},
			handleRoleClose(done) {
				done();
			},
			// 搜索
			onSearch(data) {
				// todo 清空条件
				this.currentPage = 1
				this.pageSize = 10
				this.searchData = data
				this.getUserListEvent()
			},
			// 新增
			onInsert() {
				const objOption = {
					label: '密码',
					type: 'input',
					key: 'password',
					props: {
						placeholder: '请输入密码',
						type: 'password'
					}
				}

				this.editFormRules.password[0].required = true
				const arr = this.editFormOptions.filter(item => item.label === '密码')
				if (arr.length <= 0) {
					this.editFormOptions.splice(2, 0, objOption)
				}
				const tempTree = [...this.treeData]
				// 组织机构激活
				this.setTreeDisabled(tempTree, false)
				this.$set(this.editFormOptions[0].props, 'options', tempTree)
				this.dialogFormCurrent = {}

				this.dialogFormCurrent.orgId = this.orgId;
				this.getDepList(0)
				this.openDialog()
			},
			// 组织选项是否允许编辑
			setTreeDisabled(array, disabled) {
				if (array && array.length > 0) {
					array.forEach(item => {
						item['disabled'] = disabled
						if ('children' in item) {
							this.setTreeDisabled(item.children, disabled)
						}
					})
				}
			},
			// 每页显示条数
			handleSizeChange(val) {
				this.pageSize = val
				this.getUserListEvent()
			},
			// 当前页数
			handleCurrentChange(val) {
				this.currentPage = val
				this.getUserListEvent()
			},
			
		}
	}
</script>

<style scoped lang="scss">
	.box-card {
		margin: 0px;
		height: calc(100vh - 120px);
		padding: 0px;

		.el-card__body {
			padding: 0;
		}

		.el-table {
			margin-top: 20px;
		}

		.el-pagination {
			text-align: right;
		}
	}

	/*.abc-header {*/
	/*  color: #0000ff;*/
	/*}*/
	/*.abc {*/
	/*  font-weight: bold;*/
	/*  color: #e53939;*/
	/*}*/
	.selectRole {
		padding: 30px;
		box-sizing: border-box;

		.el-select {
			width: 100%;
		}
	}

	::v-deep .el-tree>.el-tree-node {
		min-width: 100%;
		display: inline-block;
		overflow: auto;
	}
</style>
<style lang="css">
	.el-tooltip__popper,
	.el-tooltip__popper.is-dark {
		background: #FFFFFF;
		max-width: 400px;
		border-radius: 4px;
		border: 1px solid #e6ebf5;
		padding: 12px;
		color: black;
		line-height: 180%;
		-webkit-box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	}

	.el-tooltip__popper[x-placement^=top] .popper__arrow {
		bottom: -6px;
		left: 50%;
		margin-right: 3px;
		border-top-color: #FFFFFF;
		border-bottom-width: 0;
		-webkit-filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.1));
		filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
	}

	.el-tooltip__popper[x-placement^=top] .popper__arrow:after {
		position: absolute;
		display: block;
		width: 0;
		height: 0;
		border-color: transparent;
		border-style: solid;
	}

	.el-col-4 {
		margin-left: 10px;
		margin-bottom: 10px;
	}

	.el-form .el-col-4:nth-child(6) {
		margin-left: 82px;
	}

	.is-current>.el-tree-node__content {
		color: #ff4d4f;
	}

	.el-card__body {
		padding: 20px;
	}
	.el-button--text{
		display:none !important;
	}
	::v-deep .e-btn-box[data-v-6e4cbc8f] button{
		display:none !important;
	}
</style>